// Describe: 发送消息
package cmd

import (
	"context"
	"github.com/cheggaaa/pb/v3"
	"github.com/rs/zerolog/log"
	"github.com/spf13/cobra"
	"io"
	"wormhole/pkg/clientx"
	"wormhole/protos/hole"
)

var sendCmd = &cobra.Command{
	Use:     "send",
	Aliases: []string{"s"},
	Short:   "发送文本消息或文件",
	Long: `
支持指定设备方式:1.列表序号 2.设备ip 3.用户名
支持发送文本信息和文件,优先匹配文件
1、wormhole send 0 "this is message"
2、wormhole send 192.168.1.108 /path/of/file
`,
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 {
			log.Warn().Msg("无效的参数")
			_ = cmd.Help()
		} else {
			c, err := clientx.NewLocalClient()
			if err != nil {
				log.Fatal().Err(err).Send()
			}
			msg := &hole.Message{
				To:   args[0],
				Data: args[1],
			}
			sendClient, err := c.SendAuto(context.Background(), msg)
			if err != nil {
				log.Fatal().Msg("本地服务离线")
			}
			var bar *pb.ProgressBar
			isFirst := true
			for {
				progress, err := sendClient.Recv()
				if err == io.EOF {
					return
				}
				if err != nil {
					log.Err(err).Send()
					return
				}
				if progress.Total == 1 {
					if isFirst {
						isFirst = false
						bar = pb.New64(progress.Size)
						bar.Set(pb.Bytes, true)
						bar.Start()
						defer bar.Finish()
					}
					bar.SetCurrent(progress.Current)
				} else {
					if isFirst {
						isFirst = false
						bar = pb.Start64(progress.Total)
						defer bar.Finish()
					}
					bar.SetCurrent(progress.Index)
				}
			}
		}
	},
}

func init() {
	rootCmd.AddCommand(sendCmd)
}
